package l1j.opqlo.移民;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.server.DatabaseFactoryLogin;
import l1j.server.server.datatables.CharObjidTable;
import l1j.server.server.datatables.lock.AccountReading;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.templates.L1Account;
import l1j.server.server.utils.SQLUtil;

public class checkTable {


	private static checkTable _instance ;

	private static final Logger _log = Logger.getLogger(checkTable.class.getName());


	public static checkTable get(){
		if(_instance == null){
			_instance = new checkTable();
		}
		return _instance;
	}

	public void inset(final L1PcInstance pc){
		Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		L1Account account = AccountReading.get().getAccount(pc.getAccountName());
		if(account == null){
			return;
		}
//
//		L1World.getInstance().removeTradeInventory(pc.getId());
//
//		for(final L1PcInstance buddys : L1World.getInstance().getAllPlayers()){
//			//BuddyTable.getInstance().removeBuddy(buddys.getId(), pc_name);
//			if(pc != buddys){
//				BuddyTable.getInstance().getBuddyTable(buddys.getId()).remove(pc.getName());
//			}
//		}
//		final String name = pc.getName();
//		final L1Clan clan = WorldClan.get().getClan(pc.getClanname());
//		if (clan != null) {
//			clan.delMemberName(name);
//		}
//		// 已創人物數量
//		final int countCharacters = account.get_countCharacters();
//		account.set_countCharacters(countCharacters - 1);
//
//		// 刪除人物
//		try {
//			CharacterTable.getInstance().deleteCharacter(pc.getAccountName(), name);
//		} catch (Exception e1) {
//			// TODO 自動產生的 catch 區塊
//			e1.printStackTrace();
//		}
//
//		// 移出已用名稱清單
//		CharObjidTable.get().charRemove(name);
		try {
			con = DatabaseFactoryServer.get().getConnection();
			pstm = con.prepareStatement("INSERT INTO `z_opqlo_migrate` SET Account_name =? , PassWorld =? , name_1 =? , objid_1 =? , name_2 =? , objid_2 =? , newAccount =?");//"INSERT INTO ban_ip SET ip=?, host=?, mask=?"
			pstm.setString(1, account.get_login());
			pstm.setString(2, account.get_password());
			pstm.setString(3, pc.getName());
			pstm.setInt(4, pc.getId());

			final int id = getSecondPcId(account.get_login() , pc.getId());
			if( id >0){
				pstm.setString(5, CharObjidTable.get().isChar(id));
				pstm.setInt(6, id);
			}else{
				pstm.setString(5, "");
				pstm.setInt(6, 0);
			}
			pstm.setString(7, pc.getnewAccount().toString().toLowerCase());
			pstm.execute();

		} catch (final SQLException e) {
			_log.log(Level.SEVERE,e.getLocalizedMessage(), e);
		} catch (final Exception e) {
			_log.log(Level.SEVERE,e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(rs);
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
		create(pc.getnewAccount().toString().toLowerCase() , account.get_password() , account.get_ip() , account.get_mac() , account.get_NoUncodesPSW());
	}


	private int getSecondPcId(final String login , final int id){
		Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		int objid = 0;
		try {
			con = DatabaseFactoryLogin.get().getConnection();
			pstm = con.prepareStatement("SELECT * FROM characters WHERE account_name =?");
			pstm.setString(1, login);
			rs = pstm.executeQuery();
			while (rs.next()) {
				final int objid2 = rs.getInt("objid");
				if(objid2 !=id ){
					objid = objid2;
					break;
				}
			}
		} catch (final SQLException e) {
			_log.log(Level.SEVERE,e.getLocalizedMessage(), e);
			System.out.println("getSecondPcId異常");
		} finally {
			SQLUtil.close(rs);
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
		return objid;

	}


	/**
	 * 建立帳號資料
	 * @param loginName 帳號
	 * @param pwd 密碼
	 * @param ip IP位置
	 * @param host MAC位置
	 * @param spwd 超級密碼
	 * @return L1Account
	 */
	private void create(final String loginName, final String pwd,final String ip, final String host, final String nouncodepsw) {
		Connection cn = null;
		PreparedStatement ps = null;
		try {
			final Timestamp lastactive = new Timestamp(System.currentTimeMillis());

			final L1Account value = new L1Account();
			value.set_login(loginName.toLowerCase());
			value.set_password(pwd);
			value.set_lastactive(lastactive);
			value.set_access_level(0);
			value.set_ip(ip);
			value.set_mac(host);
			value.set_character_slot(0);
			//			value.set_spw(spwd);
			value.set_warehouse(-256);
			value.set_countCharacters(0);
			value.set_isLoad(false);
			value.set_NoUncodePSW(nouncodepsw);

			cn = DatabaseFactoryServer.get().getConnection();
			final String sqlstr =
					"INSERT INTO `accounts` SET `login`=?,`password`=?," +
							"`lastactive`=?,`access_level`=?,`ip`=?," +
							"`host`=?,`character_slot`=?, `nouncodepsw` =?, `banned`=?";

			ps = cn.prepareStatement(sqlstr);
			int i = 0;
			ps.setString(++i, value.get_login().toLowerCase());
			ps.setString(++i, value.get_password());
			ps.setTimestamp(++i, value.get_lastactive());
			ps.setInt(++i, 0);
			ps.setString(++i, value.get_ip());
			ps.setString(++i, value.get_mac());
			ps.setInt(++i, 0);
			ps.setString(++i, value.get_NoUncodesPSW());
			ps.setInt(++i, 1);
			ps.execute();
			_log.info("移民帳號建立: " + value.get_login());
		} catch (final SQLException e) {
			_log.log(Level.SEVERE ,e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(ps);
			SQLUtil.close(cn);
		}
	}


}
